package com.magenta.maxoptra.gis.service;

import com.magenta.maxoptra.gis.GeographicCoordinates;
import com.magenta.maxoptra.gis.PersistedCache;
import com.magenta.maxoptra.gis.ProvidersRegistry;
import com.magenta.maxoptra.gis.RouteRequestRecordPK;
import com.magenta.maxoptra.gis.commons.Logger;
import com.magenta.maxoptra.gis.commons.Pair;
import com.magenta.maxoptra.gis.commons.Quadruple;
import com.magenta.maxoptra.gis.util.Apis;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import java.util.ArrayList;

@MessageDriven(mappedName = PersistedCacheListener.JNDI_NAME,
        messageListenerInterface = MessageListener.class,
        activationConfig = {
                @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
                @ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/persisted_cache"),
                @ActivationConfigProperty(propertyName = "maxSession", propertyValue = "5")
        }, name = "PersistedCacheListenerMDB")
public class PersistedCacheListener implements MessageListener {

    final static String JNDI_NAME = "PersistedCacheListener";

    protected final Logger logger = new Logger(getClass());

    @EJB
    PersistedCache persistedCache;

    @EJB
    ProvidersRegistry providersRegistry;

    public void onMessage(Message message) {
        try {
            ArrayList<Pair<GeographicCoordinates, Quadruple>> messageObject =
                    (ArrayList<Pair<GeographicCoordinates, Quadruple>>) ((ObjectMessage) message).getObject();
            Integer fromLat = message.getIntProperty("fromLat");
            Integer fromLon = message.getIntProperty("fromLon");
            String providerName = message.getStringProperty("providerName");
            String versionApi = message.getStringProperty("versionApi");
            String discriminator = message.getStringProperty("discriminator");

            for (Pair<GeographicCoordinates, Quadruple> pair: messageObject) {
                final GeographicCoordinates coordinateTo = pair.getFirst();
                final RouteRequestRecordPK pk = new RouteRequestRecordPK(
                        providerName, versionApi, discriminator, fromLat, fromLon,
                        coordinateTo.getLatitudeInteger(), coordinateTo.getLongitudeInteger());
                persistedCache.persistRouteInfo(pk, pair.getSecond());
                providersRegistry.assignCID(Apis.cid(providerName, versionApi, discriminator), providerName, versionApi, discriminator);
            }
        } catch (JMSException e) {
            logger.error("Message processing failed: ", e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}
